/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.cs.util.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * MultiValuedMap implements Map interface.
 * It that can be used for storing multiple values for a single key.
 * @param <K>
 * @param <V> 
 * @author dimitris@jmike.gr
 */
public class MultiValuedMap<K, V> extends HashMap<K, List<V>> implements Map<K, List<V>> {

    public MultiValuedMap() {
        super();
    }

    /**
     * Add a value to the current list of values for the supplied key.
     * @param key
     * @param value
     */
    public void add(K key, V value) {
        if (super.containsKey(key)) {//map already contains key
            super.get(key).add(value);
        } else {//map does not contain key
            ArrayList<V> list = new ArrayList<V>();
            list.add(value);
            super.put(key, list);
        }
    }

    /**
     * A shortcut to get the first value of the supplied key.
     * @param key
     * @return
     */
    public V getFirst(K key) {
        List<V> list = super.get(key);
        if (list != null) {//map contains key
            return list.get(0);
        } else {//map does not contain key
            return null;
        }
    }

    /**
     * Counts the values of the designated key.
     * If the designated key does not exists, the function returns 0.
     * @param key
     * @return
     */
    public int valueSize(K key) {
        List<V> list = super.get(key);
        if (list != null) {//map contains key
            return list.size();
        } else {//map does not contain key
            return 0;
        }
    }
}
